/**
 * @file     swapPairs.js
 * @brief    [24. 两两交换链表中的节点](https://leetcode.cn/problems/swap-nodes-in-pairs/description/)
 * @author   Zhu
 * @date     2023-06-18 22:38
 */

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function (head) {
    const dummy = new ListNode();
    dummy.next = head;

    let pre = dummy;
    let cur = head;

    while (cur) {
        const nxt = cur.next;
        if (nxt) {
            const nxtCur = nxt.next;
            pre.next = nxt;
            nxt.next = cur;
            cur.next = null;

            pre = cur;
            cur = nxtCur;
        } else {
            pre.next = cur;
            break;
        }
    }

    return dummy.next;
};

/**
 * 递归
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function (head) {
    if (head == null || head.next == null) return head;

    const nxt = head.next;
    head.next = swapPairs(nxt.next);
    nxt.next = head;

    return nxt;
};
